package run.siyuan.manag.security;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import run.siyuan.common.exception.ExceptionProperties;
import run.siyuan.manag.entity.SysUser;
import run.siyuan.manag.entity.jwt.JwtUserDetails;
import run.siyuan.manag.security.GrantedAuthorityImpl;
import run.siyuan.manag.service.SysUserService;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @program: sy-auth-manag
 * @description:
 * @author: SY
 * @create: 2021-01-14 20:16
 **/
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService userService;
    @Autowired
    private ExceptionProperties properties;

    /**
     * spring security在认证过程中需要查找用户，会调用UserDetailsService的loadUserByUsername方法得到一个UserDetails
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", username);
        SysUser sysUser = userService.getOne(queryWrapper);
        if (ObjectUtil.isEmpty(sysUser)) {
            throw new UsernameNotFoundException(properties.getCodeName("50006"));
        }
        Set<String> permissions = userService.findPermissions(sysUser.getName());
        List<GrantedAuthorityImpl> grantedAuthorities = permissions.stream().map(GrantedAuthorityImpl::new).collect(Collectors.toList());
        return new JwtUserDetails(sysUser.getName(), sysUser.getPassword(), sysUser.getSalt(), grantedAuthorities);
    }
}